package controller.ucartc;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.TreeMap;

/**
 * Created by PCG on 2016/10/14.
 */
@Controller
public class SdkPayController {

    String gateWay = "https://tc.10101111.com/tc-gateway/";

    String interFace = "sdkpay/pay";

        @RequestMapping(value = "sdk/topay.do_",produces = "text/html;charset=utf-8")
    @ResponseBody
    public String toPay(HttpServletRequest request,HttpServletResponse response){
        String result = toHtmlPay();
        return result;
    }

    private String toHtmlPay(){
        Map<String,String> params = new TreeMap<String, String>();
        params.put("b_accName","eposmmcused");
        params.put("b_busiId","41414324");
        params.put("b_money","0.01");
        params.put("b_notifyUrl","http://10.101.44.119:8083/cartptest/tc/testreturnpage.do_");
        params.put("b_sourceId","p_alipay");
        params.put("b_desc","神州买卖车产品");
      //  params.put("e_unify_type","NATIVE");
//        params.put("e_aliType","1");//1：wap ,2:new wap ,0:web
//        params.put("e_client_ip","127.0.0.1");
//        params.put("e_order_timeout","1m");
        params.put("tc_customized_order_id",new SimpleDateFormat("yyyyMMdd HH:mm:ss").format(new Date()));
        String sign = getSign("q1w2e3r4t5y6u7i8o9p0",params);
        String url = "";
        for (Map.Entry<String,String> entry:params.entrySet()){
            String name = entry.getKey();
            url += name + "=" + entry.getValue() + "&";
        }
        url += "b_sign="+sign;

        HttpsUtils hs = new HttpsUtils();
        return hs.postConnection(gateWay + interFace, url);
    }

    public String getSign(String key,Map<String,String> paramMap){

        TreeMap<String,String> signMap = new TreeMap<String,String>();
        for (String paramKey : paramMap.keySet()) {
            signMap.put(paramKey, paramMap.get(paramKey));
        }
        String content = "";
        for (String keyName : signMap.keySet()) {
            content += keyName + "=" + signMap.get(keyName) + ";";
        }
        return DigestUtils.md5Hex(content + "key=" + key);

    }

    @RequestMapping("sdk/testreturnpage.do_")
    public String testReturnPage(HttpServletRequest request,HttpServletResponse response) throws Exception{
        //加入固定标记，通知交易平台回调成功
        response.addHeader("CAR_TC", Boolean.TRUE.toString());
        return "/jsp/testSuccess.jsp";
    }

}
